import { useRequest } from "ahooks";
import { Button, Modal, Pagination, Table, TableColumnsType } from "antd";
import React, { useState } from "react";
import { useParams } from "react-router-dom";
import { STAT_PAGE_SIZE } from "../../../constants";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import {
  deleteAnswerService,
  getQuestionStatListService,
} from "../../../services/question";
import { ComponentInfoType } from "../../../store/componentsReducer";
import styles from "./PageStat.module.scss";
import { ExclamationCircleOutlined } from "@ant-design/icons";

type PropsType = {
  config: {
    selectedComponentId: string;
    setSelectedComponentId: (id: string) => void;
    setSelectedComponentType: (type: string) => void;
  };
};

type DataType = {
  id: string;
  type: string;
  title: string;
  props: any;
};

const { confirm } = Modal;

const PageStat: React.FC<PropsType> = (props: PropsType) => {
  const {
    config: {
      selectedComponentId,
      setSelectedComponentId,
      setSelectedComponentType,
    },
  } = props;
  const { id = "" } = useParams();
  const [total, setTotal] = useState(0);
  const [list, setList] = useState([]);
  const { componentList } = useGetComponentInfo();

  const columns: TableColumnsType<DataType> = [
    {
      title: "答卷时间",
      dataIndex: "createdAt",
      render: (text: string) => {
        return new Date(text).toLocaleString();
      },
      width: "200px",
    },
  ];

  componentList
    .filter((c) => !["questionTitle", "questionParagraph"].includes(c.type))
    .map((c) => {
      const { id, type, title, props = {} } = c;
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      const colTitle = props!.title || title;
      const column = {
        title: (
          <div
            style={{
              color: selectedComponentId === id ? "#1890ff" : "#000",
              cursor: "pointer",
            }}
            onClick={() => {
              if (selectedComponentId === id) {
                setSelectedComponentId("");
                setSelectedComponentType("");
              } else {
                setSelectedComponentId(id);
                setSelectedComponentType(type);
              }
            }}
          >
            {colTitle}
          </div>
        ),
        dataIndex: id,
        width: "200px",
      };
      columns.push(column);

      return column;
    });

  // 添加操作列
  columns.push({
    title: <div>操作</div>,
    dataIndex: "action",
    width: "200px",
    render: (_, record: DataType) => (
      <>
        <Button
          type="link"
          target="_blank"
          href={`${process.env.REACT_APP_CLIENT_URL}/prompt/${id}?answerId=${record.id}`}
        >
          查看详情
        </Button>
        <Button type="link" danger onClick={() => handleDelete(record.id)}>
          删除
        </Button>
      </>
    ),
  });

  function handleDelete(answerId: string) {
    confirm({
      title: "确定删除这条答卷记录吗？删除后无法恢复。",
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        try {
          await deleteAnswerService(id, answerId);
          refresh();
        } catch (err) {
          console.log(err);
        }
      },
    });
  }

  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(STAT_PAGE_SIZE);
  const { loading, refresh } = useRequest(
    async () => {
      const res = await getQuestionStatListService(id, {
        page,
        pageSize,
      });

      return res;
    },
    {
      refreshDeps: [id, page, pageSize],
      onSuccess(res) {
        const { total, list = [] } = res;
        setTotal(total);
        setList(list);
      },
    }
  );

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const dataSource = list.map((i: any) => {
    Object.keys(i).forEach((k) => {
      const c = componentList.find((c) => c.id === k);
      if (c) {
        const {
          type,
          props: { options, list },
        } = c as ComponentInfoType;
        if (type) {
          switch (type) {
            case "questionRadio":
              if (options) {
                const item = options.find((o) => o.value === i[k]);
                if (item) i[k] = item.label;
              }
              break;
            case "questionCheckbox":
              if (list) {
                if (Array.isArray(i[k])) {
                  i[k].forEach((v: string, index: number) => {
                    const item = list.find((o) => o.value === v);
                    if (item) i[k][index] = item.label;
                  });
                  // eslint-disable-next-line @typescript-eslint/no-explicit-any
                  i[k] = i[k].filter((j: any) => j).join("，");
                } else {
                  const item = list.find((o) => o.value === i[k]);
                  if (item) i[k] = item.label;
                }
              }
              break;
          }
        }
      }
    });

    return { ...i, key: i.id };
  });

  return (
    <>
      <Table
        loading={loading}
        columns={columns}
        dataSource={dataSource}
        pagination={false}
        scroll={{ x: 1049, y: 1210 }}
        className={styles.table}
      />
      <Pagination
        style={{
          marginTop: "20px",
          textAlign: "center",
        }}
        total={total}
        current={page}
        pageSize={pageSize}
        onChange={(page) => setPage(page)}
        onShowSizeChange={(page, pageSize) => {
          setPage(page);
          setPageSize(pageSize);
        }}
      />
    </>
  );
};

export default React.memo(PageStat);
